package com.mj.birthcalc.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.baidu.appx.BDBannerAd;
import com.baidu.appx.BDInterstitialAd;
import com.baidu.appx.BDBannerAd.BannerAdListener;
import com.baidu.appx.BDInterstitialAd.InterstitialAdListener;
import com.mj.birthcalc.R;
import com.mj.birthcalc.service.BirthcalcService;
import com.mj.birthcalc.util.NetUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 生辰八字算命
 * @author zhaominglei
 * @date 2015-4-10
 * 
 */
public class MainActivity extends Activity implements OnClickListener {
	private static final String TAG = MainActivity.class.getSimpleName();
	private static final int BEGINYEAR = 1922; //开始年份
	private static final int SELECTEDYEAR = 1986; //选择年份
	private BirthcalcService birthcalcService = new BirthcalcService();
	private boolean isExit = false;
	private TimerTask timerTask;
	private Spinner typeSpinner; //历法选择框
	private String type; //历法
	private Spinner yearSpinner; //出生年选择框
	private String year; //出生年
	private Spinner monthSpinner; //出生月选择框
	private String month; //出生月
	private Spinner daySpinner; //出生日选择框
	private String day; //出生日
	private Spinner hourSpinner; //出生时选择框
	private String hour; //出生时
	private Button queryBtn; //配对测试
	private ProgressBar queryProgressBar; //查询进度条
	private TextView resultView; //结果
	private Button appOffersButton; //推荐应用
	private RelativeLayout appxBannerContainer; //appx 容器
	private static BDBannerAd bannerAdView; //横幅广告
	private BDInterstitialAd appxInterstitialAdView; //插屏广告
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}

	private void init() {
		typeSpinner = (Spinner)findViewById(R.id.birthcalc_type_spinner);
		
		List<String> yearList = new ArrayList<String>();
		int index = 0, position = 0;
		int ENDYEAR = Integer.valueOf((String)DateFormat.format("yyyy", new Date())); //结束年份
		for (int i = BEGINYEAR; i <= ENDYEAR; i++) {
			yearList.add(String.valueOf(i));
			if (i == SELECTEDYEAR) {
				position = index;
			}
			index++;
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
		yearSpinner = (Spinner)findViewById(R.id.birthcalc_year_spinner);
		yearSpinner.setAdapter(adapter);
		yearSpinner.setSelection(position, true);
		
		monthSpinner = (Spinner)findViewById(R.id.birthcalc_month_spinner);
		daySpinner = (Spinner)findViewById(R.id.birthcalc_day_spinner);
		hourSpinner = (Spinner)findViewById(R.id.birthcalc_hour_spinner);
		queryBtn = (Button)findViewById(R.id.birthcalc_query_btn);
		queryProgressBar = (ProgressBar)findViewById(R.id.birthcalc_query_progressbar);
		resultView = (TextView)findViewById(R.id.birthcalc_result);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);
		
		queryBtn.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);
		
		//创建广告视图 发布时请使用正确的ApiKey和广告位ID
		bannerAdView = new BDBannerAd(this, "3WEqC0yhGVMmOlL16WzhF2VV",
				"hIypTezAiGQWOAIiry5skSx0");
		//设置横幅广告展示尺寸，如不设置，默认为SIZE_FLEXIBLE;
//						bannerAdView.setAdSize(BDBannerAd.SIZE_320X50);
		//设置横幅广告行为监听器
		bannerAdView.setAdListener(new BannerAdListener() {
			@Override
			public void onAdvertisementDataDidLoadFailure() {
				Log.e(TAG, "load failure");
			}
			@Override
			public void onAdvertisementDataDidLoadSuccess() {
				Log.e(TAG, "load success");
			}
			@Override
			public void onAdvertisementViewDidClick() {
				Log.e(TAG, "on click");
			}
			@Override
			public void onAdvertisementViewDidShow() {
				Log.e(TAG, "on show");
			}
			@Override
			public void onAdvertisementViewWillStartNewIntent() {
				Log.e(TAG, "leave app");
			}
		});
		appxBannerContainer = (RelativeLayout) findViewById(R.id.appx_banner_container);
		appxBannerContainer.addView(bannerAdView);
		
		//创建广告视图 发布时请使用正确的ApiKey和广告位ID
		appxInterstitialAdView = new BDInterstitialAd(this,
				"3WEqC0yhGVMmOlL16WzhF2VV", "EIs7cGmh6dqpMCdpfjWEVTac");
		//设置插屏广告行为监听器
		appxInterstitialAdView.setAdListener(new InterstitialAdListener() {
			@Override
			public void onAdvertisementDataDidLoadFailure() {
				Log.e(TAG, "load failure");
			}
			@Override
			public void onAdvertisementDataDidLoadSuccess() {
				Log.e(TAG, "load success");
			}
			@Override
			public void onAdvertisementViewDidClick() {
				Log.e(TAG, "on click");
			}
			@Override
			public void onAdvertisementViewDidHide() {
				Log.e(TAG, "on hide");
			}
			@Override
			public void onAdvertisementViewDidShow() {
				Log.e(TAG, "on show");
			}
			@Override
			public void onAdvertisementViewWillStartNewIntent() {
				Log.e(TAG, "leave");
			}
		});
		//加载广告
		appxInterstitialAdView.loadAd();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.birthcalc_query_btn:
			type = (String)typeSpinner.getSelectedItem();
			if (type == null || type.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_type_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			year = (String)yearSpinner.getSelectedItem();
			if (year == null || year.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_year_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			month = (String)monthSpinner.getSelectedItem();
			if (month == null || month.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_month_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			day = (String)daySpinner.getSelectedItem();
			if (day == null || day.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_day_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			hour = (String)hourSpinner.getSelectedItem();
			if (hour == null || hour.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_hour_prompt, Toast.LENGTH_SHORT).show();
				return;
			}
			resultView.setText("");
			
			getBirthcalcInfo();
			break;
		
		case R.id.appOffersButton:
			//展示插屏广告前先请先检查下广告是否加载完毕
			if (appxInterstitialAdView.isLoaded()) {
				appxInterstitialAdView.showAd();
			} else {
				Log.i(TAG, "AppX Interstitial Ad is not ready");
				appxInterstitialAdView.loadAd();
			}
			break;
			
		default:
			break;
		}
	}
	
	private void getBirthcalcInfo() {
		if (NetUtils.isConnected(getApplicationContext())) {
			queryProgressBar.setVisibility(View.VISIBLE);
			new BirthcalcInfoAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}
	
	public class BirthcalcInfoAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			return birthcalcService.getBirthcalcInfo(type, year, month, day, hour);
		}

		@Override
		protected void onPostExecute(String result) {
			queryProgressBar.setVisibility(View.GONE);
			if (result != null && !result.equals("")) {
				resultView.setText(Html.fromHtml(result));
			} else {
				Toast.makeText(getApplicationContext(), R.string.birthcalc_error1, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
